package com.keda;

import com.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class test_add {
    public static void main(String[] args) throws IOException {

        //创建es 客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200))
        );

        // 添加数据
         IndexRequest  request=new IndexRequest();
         //向索引  user 中添加数据  并设置id为1001
         request.index("user").id("1001");

        User user = new User();
        user.setName("张三");
        user.setSex("男");
        user.setAge(20);

        //注意  向es中存储数据必须是 json 格式
        ObjectMapper mapper = new ObjectMapper();
        String userjson = mapper.writeValueAsString(user);
        request.source(userjson, XContentType.JSON);


        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());


        //http://127.0.0.1:9200/user/_doc/1001    可以查到张三了


        //关闭es客户端
        try {
            esClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
